package controller

import (
	"errors"
	"time"

	"github.com/RaymondCode/simple-demo/Dao"
	"github.com/RaymondCode/simple-demo/model"
	"github.com/dgrijalva/jwt-go"
)

const secretKey = "a10IJD32JA2add"

// GenerateToken 使用密钥、user对象的信息和当前时间生成一个token并返回
func GenerateToken(username, password string) string {
	claims := jwt.MapClaims{
		"username": username,
		"password": password,
		"exp":      time.Now().Add(time.Hour * 72).Unix(), // token 72小时过期
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	if res, err := token.SignedString([]byte(secretKey)); err != nil {
		return ""
	} else {
		return res
	}
}

// ParseToken 解析token并返回user对象
func ParseToken(tokenString string) (model.User, error) {
	var user model.User

	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, errors.New("unexpected signing method")
		}
		return []byte(secretKey), nil
	})

	if err != nil {
		return user, err
	}

	if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
		username, password := claims["username"].(string), claims["password"].(string)
		if err := Dao.DB.Where("name = ? AND password = ?", username, password).First(&user).Error; err != nil {
			return user, err
		}
		return user, nil
	}

	return user, errors.New("invalid token")
}
